package com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity;

import android.Manifest;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.utils.FileUtil;
import com.ninetaildemonfox.zdl.socialproject.utils.FileUtils;
import com.ninetaildemonfox.zdl.socialproject.utils.GetPathFromUri;
import com.ninetaildemonfox.zdl.socialproject.utils.PlayView;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.ninetaildemonfox.zdl.socialproject.utils.VideoControlView;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.orhanobut.logger.Logger;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

import static mabeijianxi.camera.util.DeviceUtils.getScreenHeight;
import static mabeijianxi.camera.util.DeviceUtils.getScreenWidth;

/**
 * @author NineTailDemonFox
 * @date 2019/8/21 8:56
 * 功能描述：录像机
 * <p>
 * stopRecord(false);  停止录制方法
 * <p>
 * 联系方式：1037438704@qq.com
 */
public class CameraActivity extends AppCompatActivity implements SurfaceHolder.Callback, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.sv_record)
    SurfaceView svRecord;
    @BindView(R.id.ll_xiangce)
    LinearLayout ll_xiangce;
    @BindView(R.id.tv_quxiao)
    TextView tv_quxiao;
    @BindView(R.id.tv_wancheng)
    TextView tv_wancheng;
    @BindView(R.id.imageView)
    ImageView imageView;
    //    @BindView(R.id.playview)
//    PlayView playView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private MediaRecorder mediaRecorder;
    //当前打开的摄像头标记 1--后，2--前
    private int currentCameraType = -1;
    private File temFile;
    private MyTimer myTimer;
    private static final long TIME_MAX = 15 * 1000;
    private static final long TIME_INTERVAL = 500;
    private static final int RC_STORAGE = 1001;
    private Camera.Size size;
    @BindView(R.id.control_view)
    VideoControlView control_view;
    boolean flagRecord = false;//是否正在录像
    int rotationRecord = 90;
    int rotationFlag = 90;
    int frontRotate;
    int frontOri;
    int cameraType = 0;
    int cameraFlag = 1; //1为后置
    int flashType;
    private String videoPath;
    private File videoFile;
    private Bitmap videoThumbnail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        initView();
        initData();
    }

    private long duration = -1;

    private void initData() {
        control_view.setOnRecordListener(new VideoControlView.OnRecordListener() {
            @Override
            public void OnRecordStartClick() {
                clickRecord();
            }

            @Override
            public void OnFinish(int resultCode) {
                stopRecord(false);
            }
        });
    }

    private void initView() {
        //        获取权限
        requestPermision();
        ButterKnife.bind(this);
        ll_xiangce.setVisibility(View.GONE);
        control_view.setMaxTime(10);
        surfaceHolder = svRecord.getHolder();
        surfaceHolder.addCallback(this);
        //设置一些参数方便后面绘图
        svRecord.setFocusable(true);
        svRecord.setKeepScreenOn(true);
        svRecord.setFocusableInTouchMode(true);
    }

    @OnClick({R.id.tv_quxiao, R.id.imageView,
            R.id.tv_wancheng, R.id.ll_xiangce})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //取消
            case R.id.tv_quxiao:
                finish();
                break;
            //确定
            case R.id.tv_wancheng:
                if (videoFile != null) {
                    finish();
                    return;
                }
                if (videoPath != null) {
                    Bundle bundle = new Bundle();
                    Intent i = new Intent();
                    bundle.putString("path", videoPath);
                    i.putExtras(bundle);
                    setResult(RESULT_OK, i);
                    finish();
                } else {
                    Toast.makeText(this, "请拍摄视频", Toast.LENGTH_SHORT).show();
                }
                break;
            //切换摄像头
            case R.id.imageView:
                stopPreview();
                if (currentCameraType == 1) {
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
                    currentCameraType = 2;
                } else {
                    camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                    currentCameraType = 1;
                }
                startPreview();
                break;
            case R.id.ll_xiangce:
                selShipin();
                break;
            default:
        }
    }

    /**
     * 录制按键
     */
    private void clickRecord() {
        if (!flagRecord) {
            startRecord();
        } else {
            stopRecord(false);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (flagRecord) {
                stopRecord(false);
                if (camera != null && cameraType == 0) {
                    //关闭后置摄像头闪光灯
                    camera.lock();
                    FlashLogic(camera.getParameters(), 0, true);
                    camera.unlock();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 开始录制
     */
    private void startRecord() {
        if (mediaRecorder == null) {
            mediaRecorder = new MediaRecorder();
        }
        temFile = getTemFile();


        try {
            camera.unlock();
            mediaRecorder.setCamera(camera);
            //从相机采集视频
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
            // 从麦克采集音频信息
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            //编码格式
            mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            mediaRecorder.setVideoSize(size.width, size.height);

            //每秒的帧数
            mediaRecorder.setVideoFrameRate(24);
            // 设置帧频率，然后就清晰了
            mediaRecorder.setVideoEncodingBitRate(1 * 1024 * 1024 * 100);


            mediaRecorder.setOutputFile(temFile.getAbsolutePath());
            mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
            //解决录制视频, 播放器横向问题
            if (currentCameraType == 1) {
                //后置
                mediaRecorder.setOrientationHint(90);
            } else {
                //前置
                mediaRecorder.setOrientationHint(270);
            }
            mediaRecorder.prepare();
            //正式录制
            mediaRecorder.start();

            myTimer = new MyTimer(TIME_MAX, TIME_INTERVAL);
            myTimer.start();

            showtoast("开始录制");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化相机
     *
     * @param type    前后的类型
     * @param flashDo 赏光灯是否工作
     */
    private List<Camera.Size> mSupportedPreviewSizes;

    private Camera.Size optimalPreviewSize;

    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) {
            return null;
        }

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) {
                continue;
            }
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    /**
     * 旋转前置摄像头为正的
     */
    private void frontCameraRotate() {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(1, info);
        int degrees = getDisplayRotation(this);
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360; // compensate the mirror
        } else { // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        frontOri = info.orientation;
        frontRotate = result;
    }

    /**
     * 获取旋转角度
     */
    private int getDisplayRotation(Activity activity) {
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        switch (rotation) {
            case Surface.ROTATION_0:
                return 0;
            case Surface.ROTATION_90:
                return 90;
            case Surface.ROTATION_180:
                return 180;
            case Surface.ROTATION_270:
                return 270;
        }
        return 0;
    }

    /**
     * 释放摄像头资源
     */
    private void releaseCamera() {
        try {
            if (camera != null) {
                camera.setPreviewCallback(null);
                camera.stopPreview();
                camera.lock();
                camera.release();
                camera = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String videoDir() {
        File sampleDir = new File(FileUtils.getAppPath());
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        File vecordDir = sampleDir;
        // 创建文件
        try {
            videoFile = File.createTempFile("recording", ".mp4", vecordDir);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        startPreview();
    }

    /**
     * 获取临时文件目录
     *
     * @return
     */
    private File getTemFile() {
        String basePath = Environment.getExternalStorageDirectory().getPath() + "/doudemo/";

        File baseFile = new File(basePath);
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }

        File temp = new File(basePath + System.currentTimeMillis() + ".mp4");

        return temp;
    }

    /**
     * 停止录制
     */
    private void stopRecord(boolean delete) {
        if (mediaRecorder == null) {
            return;
        }
        if (myTimer != null) {
            myTimer.cancel();
        }

        try {
            mediaRecorder.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mediaRecorder.reset();
        mediaRecorder.release();
        mediaRecorder = null;
        if (camera != null) {
            camera.lock();
        }

        if (delete) {
            if (temFile != null && temFile.exists()) {
                temFile.delete();
            }
        } else {
            //停止预览
            stopPreview();
            videoPath = temFile.getPath();
        }
        showtoast("停止录制");
    }


    /**
     * 开始预览
     */
    private void startPreview() {
        if (svRecord == null || surfaceHolder == null) {
            return;
        }
        if (camera == null) {
            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            currentCameraType = 1;
        }
        try {
            camera.setPreviewDisplay(surfaceHolder);
            Camera.Parameters parameters = camera.getParameters();
            camera.setDisplayOrientation(90);
            //实现Camera自动对焦
            List<String> focusModes = parameters.getSupportedFocusModes();
            if (focusModes != null) {
                for (String mode : focusModes) {
                    mode.contains("continuous-video");
                    parameters.setFocusMode("continuous-video");
                }
            }

            List<Camera.Size> sizes = parameters.getSupportedVideoSizes();
            if (sizes.size() > 0) {
                size = sizes.get(sizes.size() - 1);
            }
            try {
                //oppo手机报错
                camera.setParameters(parameters);
                camera.startPreview();
            } catch (RuntimeException e) {
                camera.startPreview();
            }

        } catch (IOException e) {
            camera.startPreview();
        }

    }

    /**
     * 停止预览
     */
    private void stopPreview() {
        //停止预览并释放摄像头资源
        if (camera == null) {
            return;
        }

        camera.setPreviewCallback(null);
        camera.stopPreview();
        camera.release();
        camera = null;
    }


    @Override
    protected void onStop() {
        super.onStop();
        stopPreview();
        stopRecord(true);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        surfaceHolder = holder;
        requestPermision();
    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        surfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        //停止预览并释放摄像头资源
        stopPreview();
        //停止录制
        startRecord();
    }

    private void requestPermision() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Already have permission, do the thing
            startPreview();
            // ...
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我们的app需要以下权限",
                    RC_STORAGE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // Some permissions have been granted
        startPreview();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // Some permissions have been denied
        finish();
    }


    public class MyTimer extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            int progress = (int) ((TIME_MAX - millisUntilFinished) / (double) TIME_MAX * 100);
            Log.e("cheng", "millisUntilFinished=" + progress);
//            pbRecord.setProgress(progress);

        }

        @Override
        public void onFinish() {
            stopRecord(false);
        }
    }

    /**
     * @param s
     */
    public void showtoast(@NonNull String s) {
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    /**
     * 闪光灯逻辑
     *
     * @param p    相机参数
     * @param type 打开还是关闭
     * @param isOn 是否启动
     */
    private void FlashLogic(Camera.Parameters p, int type, boolean isOn) {
        flashType = type;
        if (type == 0) {
            if (isOn) {
                p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(p);
            }
        } else {
            if (isOn) {
                p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(p);
            }
        }
    }

    /**
     * 旋转界面UI
     */
    private OrientationEventListener orientationEventListener;

    private void rotationUIListener() {
        orientationEventListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int rotation) {
                if (!flagRecord) {
                    if (((rotation >= 0) && (rotation <= 30)) || (rotation >= 330)) {
                        // 竖屏拍摄
                        if (rotationFlag != 0) {
                            //旋转logo
                            rotationAnimation(rotationFlag, 0);
                            //这是竖屏视频需要的角度
                            rotationRecord = 90;
                            //这是记录当前角度的flag
                            rotationFlag = 0;
                        }
                    } else if (((rotation >= 230) && (rotation <= 310))) {
                        // 横屏拍摄
                        if (rotationFlag != 90) {
                            //旋转logo
                            rotationAnimation(rotationFlag, 90);
                            //这是正横屏视频需要的角度
                            rotationRecord = 0;
                            //这是记录当前角度的flag
                            rotationFlag = 90;
                        }
                    } else if (rotation > 30 && rotation < 95) {
                        // 反横屏拍摄
                        if (rotationFlag != 270) {
                            //旋转logo
                            rotationAnimation(rotationFlag, 270);
                            //这是反横屏视频需要的角度
                            rotationRecord = 180;
                            //这是记录当前角度的flag
                            rotationFlag = 270;
                        }
                    }
                }
            }
        };
        orientationEventListener.enable();
    }


    private void rotationAnimation(int from, int to) {
        ValueAnimator progressAnimator = ValueAnimator.ofInt(from, to);
        progressAnimator.setDuration(300);
        progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
            }
        });
        progressAnimator.start();
    }


    public void selShipin() {
        if (isMIUI()) {//是否是小米设备,是的话用到弹窗选取入口的方法去选取视频
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "video/*");
            startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), 6);
        } else {//直接跳到系统相册去选取视频
            Intent intent = new Intent();
            if (Build.VERSION.SDK_INT < 19) {
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setType("video/*");
            } else {
                intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("video/*");
            }
            startActivityForResult(Intent.createChooser(intent, "选择要导入的视频"), 66);
        }

    }

    public static boolean isMIUI() {
        String manufacturer = Build.MANUFACTURER;
        //这个字符串可以自己定义,例如判断华为就填写huawei,魅族就填写meizu
        if ("xiaomi".equalsIgnoreCase(manufacturer)) {
            return true;
        }
        return false;
    }

    private void showCameraPermission() {
        Toast.makeText(this, "您没有开启相机权限或者录音权限", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 66 && resultCode == RESULT_OK && null != data) {
            Uri selectedVideo = data.getData();
            videoPath = FileUtil.getFilePathByUri(this, selectedVideo);
            ToastUtil.show("拍摄路径======845======" + videoPath);
            videoThumbnail = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MICRO_KIND);
        }
        if (requestCode == 6 && resultCode == RESULT_OK && null != data) {
            videoPath = GetPathFromUri.getPath(this, data.getData());
            videoThumbnail = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MICRO_KIND);
            ToastUtil.show("拍摄路径=========860===========" + videoPath);

            if (videoThumbnail != null) {
            } else {
                Toast.makeText(this, "获取缩略图失败拉！", Toast.LENGTH_SHORT).show();
            }
        }
        if (resultCode != RESULT_OK) {
            return;
        }
    }
}